//
//  MakeWishDetailViewController.m
//  一点互助
//
//  Created by rimi on 16/8/26.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "MakeWishDetailViewController.h"
#import "ResponseManager.h"
#import "UserState.h"
#import "UIViewController+NavagitionBar.h"
#import "FBProgressView.h"

@interface MakeWishDetailViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *dateTextField;
@property (weak, nonatomic) IBOutlet UITextField *areaTextField;
@property (strong, nonatomic) NSString *city;
@property (strong, nonatomic) NSString *province;
@property (weak, nonatomic) IBOutlet UITextField *countTextField;
@property (weak, nonatomic) IBOutlet UITextField *cellPhoneTextField;
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;
@property (weak, nonatomic) IBOutlet UIButton *reheatPublishBtn;
@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) NSMutableArray *areaDataSoure;
@property (strong, nonatomic) UIPickerView *areaPicker;
@end

@implementation MakeWishDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithRed:0.8824 green:0.8824 blue:0.8824 alpha:1.0]];
    [self addSubviews];
//    [self getAreaRequest];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}
-(void)addSubviews{
    self.dateTextField.inputView = self.datePicker;
    NSDate * senddate=[NSDate date];
    NSCalendar * cal=[NSCalendar currentCalendar];
    NSUInteger unitFlags= NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    NSInteger year=[conponent year];
    NSInteger month=[conponent month];
    NSInteger day=[conponent day];
    NSString * nsDateString= [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
    self.dateTextField.text = nsDateString;
    self.areaTextField.inputView = self.areaPicker;
    
}
-(void)getAreaRequest{
    __weak typeof(self) myself = self;
    [ResponseManager startGetRequestWithURLString:kAreaURL parameters:nil completionHandler:^(FBResponse *response) {
        if (response.success) {
            PLLOG(@"%@",response.resultValue);
            myself.areaDataSoure = [response.resultValue copy];
        }
    }];
}
-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(100, kScreenWidth, 100, 100)];
        self.datePicker.date = [NSDate date]; // 设置初始时间
//             [self.datePicker setDate:[NSDate dateWithTimeIntervalSinceNow:48 * 20 * 18] animated:YES]; // 设置时间，有动画效果
            self.datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"]; // 设置时区，中国在东八区
//            self.datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:72 * 60 * 60 * -1]; // 设置最小时间
//            self.datePicker.maximumDate = [NSDate dateWithTimeIntervalSinceNow:72 * 60 * 60]; // 设置最大时间
            self.datePicker.datePickerMode = UIDatePickerModeDate; // 设置样式
            // 以下为全部样式
            // typedef NS_ENUM(NSInteger, UIDatePickerMode) {
            //    UIDatePickerModeTime,           // 只显示时间
            //    UIDatePickerModeDate,           // 只显示日期
            //    UIDatePickerModeDateAndTime,    // 显示日期和时间
            //    UIDatePickerModeCountDownTimer  // 只显示小时和分钟 倒计时定时器
            // };
            [self.datePicker addTarget:self action:@selector(datePickerTaped:) forControlEvents:UIControlEventValueChanged]; // 添加监听器//
    }
    return _datePicker;
}
//-(void)addSubviews{
//    self.datePicker = [[UIDatePicker alloc]init];
//    self.datePicker.frame = self.view1.bounds;
//    [self.view1 addSubview:self.datePicker];

//
//}
-(void)datePickerTaped:(UIDatePicker *)sender{
    NSDate *select = [sender date]; // 获取被选中的时间
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"yy年MM月dd日"; // 设置时间和日期的格式
    NSString *dateAndTime = [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
    
    // 通过UIAlertView显示出来
    self.dateTextField.text = dateAndTime;
    
}

- (IBAction)publishBtnTaped:(id)sender {
    __weak typeof(self) myself = self;
    [FBProgressView showWithMessage:@"正在发布"];
    PLLOG(@"%@",self.dic);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dic];
    dic[@"wish_price"] = [NSNumber numberWithInteger:[self.countTextField.text integerValue]];
    dic[@"city"] = self.city;
    dic[@"province"] = self.province;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *IdDic = [defaults objectForKey:@"userInfo"];
    dic[@"user_id"] = IdDic[@"id"];
    dic[@"wish_type"] = @(1);
    dic[@"wish_end_time"] = self.dateTextField.text;
    dic[@"mobile"] = [NSNumber numberWithInteger:[self.cellPhoneTextField.text integerValue]] ;
    NSArray *documentsPathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [documentsPathArr lastObject];
    NSArray *imageArr = dic[@"pic"];
    NSMutableArray *keyArr = [NSMutableArray array];
    NSMutableArray *imagePathArr = [NSMutableArray array];
    for (int i = 0; i < imageArr.count; i++) {
        NSData *data = UIImageJPEGRepresentation(imageArr[i], 1);
        NSString *path = [documentsPath stringByAppendingPathComponent:@"tupian"];
        [data writeToFile:path atomically:YES];
        [keyArr addObject:[NSString stringWithFormat:@"pic%d",i+1]];
        [imagePathArr addObject:path];
    }
    if (imageArr.count == 0) {
           PLLOG(@"%@",dic);
        [ResponseManager startPostRequestWithURLString:kUpdateWishURL parameters:dic completionHandler:^(FBResponse *response) {
            if (response.success) {
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:1 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself.navigationController popToRootViewControllerAnimated:YES];
                }];
                PLLOG(@"%@",response.resultValue);
            }else{
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself publishBtnTaped:myself.publishBtn];
                }];
                PLLOG(@"%@",response.resultDesc);
            }
        }];

    }else{
        PLLOG(@"dic:%@,imageArr:%@,KeyArr:%@",dic,imagePathArr,keyArr);
        [ResponseManager startUploadRequestWithURLString:kUpdateWishURL parameters:dic filePathList:imagePathArr fileKeyList:keyArr completionHandler:^(FBResponse *response) {
            if (response.success) {
                [FBProgressView hide];
                PLLOG(@"%@",response.resultValue);
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:1 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself.navigationController popToRootViewControllerAnimated:YES];
                }];
            }else{
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself publishBtnTaped:myself.publishBtn];
                }];
                PLLOG(@"%@",response.resultDesc);
            }
        }];

    }
    
}
- (IBAction)reheatPublishBtnTaped:(id)sender {
    __weak typeof(self) myself = self;
    [FBProgressView showWithMessage:@"正在发布"];
    PLLOG(@"%@",self.dic);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dic];
    dic[@"wish_price"] = [NSNumber numberWithInteger:[self.countTextField.text integerValue]];
    dic[@"city"] = self.city;
    dic[@"province"] = self.province;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *IdDic = [defaults objectForKey:@"userInfo"];
    dic[@"user_id"] = IdDic[@"id"];
    dic[@"wish_type"] = @(2);
    dic[@"wish_end_time"] = self.dateTextField.text;
    dic[@"mobile"] = [NSNumber numberWithInteger:[self.cellPhoneTextField.text integerValue]] ;
    NSArray *documentsPathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [documentsPathArr lastObject];
    NSArray *imageArr = dic[@"pic"];
    NSMutableArray *keyArr = [NSMutableArray array];
    NSMutableArray *imagePathArr = [NSMutableArray array];
    for (int i = 0; i < imageArr.count; i++) {
        NSData *data = UIImageJPEGRepresentation(imageArr[i], 1);
        NSString *path = [documentsPath stringByAppendingPathComponent:@"tupian"];
        [data writeToFile:path atomically:YES];
        [keyArr addObject:[NSString stringWithFormat:@"pic%d",i+1]];
        [imagePathArr addObject:path];
    }
    if (imageArr.count == 0) {
        PLLOG(@"%@",dic);
        [ResponseManager startPostRequestWithURLString:kUpdateWishURL parameters:dic completionHandler:^(FBResponse *response) {
            if (response.success) {
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:1 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself.navigationController popToRootViewControllerAnimated:YES];
                }];
                PLLOG(@"%@",response.resultValue);
            }else{
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself publishBtnTaped:myself.publishBtn];
                }];
                PLLOG(@"%@",response.resultDesc);
            }
        }];
        
    }else{
        PLLOG(@"dic:%@,imageArr:%@,KeyArr:%@",dic,imagePathArr,keyArr);
        [ResponseManager startUploadRequestWithURLString:kUpdateWishURL parameters:dic filePathList:imagePathArr fileKeyList:keyArr completionHandler:^(FBResponse *response) {
            if (response.success) {
                [FBProgressView hide];
                PLLOG(@"%@",response.resultValue);
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:1 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself.navigationController popToRootViewControllerAnimated:YES];
                }];
            }else{
                [FBProgressView hide];
                [self addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                    [myself publishBtnTaped:myself.publishBtn];
                }];
                PLLOG(@"%@",response.resultDesc);
            }
        }];
        
    }
    

}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.publishBtn.layer.cornerRadius = self.publishBtn.bounds.size.height/2;
    self.reheatPublishBtn.layer.cornerRadius = self.reheatPublishBtn.bounds.size.height/2;
}
-(NSMutableArray *)areaDataSoure{
    if (!_areaDataSoure) {
        _areaDataSoure = [NSMutableArray array];
        NSString *path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"address.plist"];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
        _areaDataSoure = dic[@"address"];
    }
    return _areaDataSoure;
}
-(UIPickerView *)areaPicker{
    if (!_areaPicker) {
        _areaPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(100, 0, kScreenWidth, 200 * kScreenHeightScale)];
        _areaPicker.delegate = self;
    }
    return _areaPicker;
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.areaDataSoure.count;
    }else{
        NSInteger index = [pickerView selectedRowInComponent:0];
        NSArray *arr = self.areaDataSoure[index][@"sub"];
        return arr.count;
    }
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return self.areaDataSoure[row][@"name"];
    }else{
        NSInteger index = [pickerView selectedRowInComponent:0];
        return self.areaDataSoure[index][@"sub"][row][@"name"];
    }
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        [pickerView reloadComponent:1];
        NSInteger index = [pickerView selectedRowInComponent:0];
      self.areaTextField.text = [NSString stringWithFormat:@"%@%c%@",self.areaDataSoure[index][@"name"],47,self.areaDataSoure[index][@"sub"][0][@"name"]];
        self.province = self.areaDataSoure[index][@"name"];
        self.city = self.areaDataSoure[index][@"sub"][0][@"name"];
    }else{
        NSInteger index = [pickerView selectedRowInComponent:0];
        self.areaTextField.text = [NSString stringWithFormat:@"%@%c%@",self.areaDataSoure[index][@"name"],47,self.areaDataSoure[index][@"sub"][row][@"name"]];
        self.province = self.areaDataSoure[index][@"name"];
        self.city = self.areaDataSoure[index][@"sub"][row][@"name"];
    }
   

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
